<template>
    <div>
        <table>
            <tr>
                <td>编号</td>
                <td>名称</td>
                <td>价格</td>
                <td>数量</td>
                <td>操作</td>
            </tr>
            <tr v-for="i in goods_list" :key="i.id">
                <td>{{i.id}}</td>
                <td>{{i.name}}</td>
                <td>{{i.price}}</td>
                <td>{{i.counter}}</td>
                <td>
                    <button @click="buy(i.name,i.counter)">购买</button>
                </td>
            </tr>
        </table>
        <p><input type="button" value="购物车" @click="akk()"></p>
    </div>
</template>

<script>
import axios from 'axios'
export default {
    data() {
        name:'Showgoods'
        return {
            goods_list:[],
            user_id:sessionStorage.getItem('user_id'),

        }
    },
    methods: {
        buy(name,gets){
            if(this.user_id){
                //条件成立，这里购买商品的逻辑
                if(parseInt(gets)>0){
                    var len = new FormData()
                    len.append('name',name)
                    len.append('user_id',this.user_id)
                    axios({
                        url:'http://127.0.0.1:8000/app01/goods',
                        method:'post',
                        data:len
                    }).then(res=>{
                        alert(res.data.msg)
                        this.$router.go(0)
                        if(sessionStorage.getItem(name)){
                            sessionStorage.setItem(name,parseInt(sessionStorage.getItem(name))+1)
                        }else{
                            sessionStorage.setItem(name,1)
                        }
                    })
                }else{
                    alert('书籍不存在')
                }
            }else{  //用户没登陆跳转到登录页面
                this.$router.push({path:'UserLogin'})
                

            }
        },
        huo(){
            axios({
                url:'http://127.0.0.1:8000/app01/goods_api'
            }).then(res=>{
                console.log(res.data)
                this.goods_list = res.data
            })
        },
        akk(){
            if(sessionStorage.getItem("username")){
                this.$router.push({path:'GouWu'})
            }else{
                alert('未登录，前往登陆页面')
                this.$router.push({path:'UserLogin'})
            }
        }
    },
    created() {
        this.huo()
    }
}
</script>

<style scoped>

</style>
